$(function(){
	chart_index.run();
});

var chart_index = {
	run: function(){
		this._init_();
		this._start_();
		this._bind_events();
	},
	
	_init_: function(){			
		//5 * 20 = 100
		this.maxPageCount = 5;
		this.dailyPage = 2;
		this.weeklyPage = 2;
	},
	
	_start_: function(){		
		this._highlight_nav();
	},
	
	_highlight_nav: function(){
		var $li = $("#side_menu > ul > li");
		$li.eq(1).addClass("curr");
	},
	
	_bind_events: function(){		
		//scrolling
		$.scroll(function(){
			chart_index._handle_scrolling();
		});
	},	
	
	_handle_scrolling: function(){	
		var $w = $(window);
		if( ! $w.data("scrolling")){
			var query = false;
			$w.data("scrolling", true);
			if(this.dailyPage <= this.maxPageCount){
				query = true;
				this._query_daily();
			}
			
			if(this.weeklyPage <= this.maxPageCount){
				query = true;
				this._query_weekly();
			}
			
			if( ! query){
				$w.data("scrolling", false);
			}
		}		
	},
	
	_query_weekly: function(){
		var $w = $(window);
		if($w.data("querying_weekly")) {
			return;
		}
		$w.data("querying_weekly", true);
		
		var wurl = main.contextPath + "/world/music/chart/query?period=weekly&page=" + this.weeklyPage;
		var $youtube_100_loading = $("#youtube_100_div > div.loadingBox");
		$youtube_100_loading.show();
		
		$.get(wurl, function(result){
			$youtube_100_loading.before(result);
			chart_index.weeklyPage += 1;
		}).complete(function(){
			$youtube_100_loading.hide();
			$w.data("querying_weekly", false);
			$w.data("scrolling", false);
		});		
	},
	
	_query_daily: function(){
		var $w = $(window);
		if($w.data("querying_daily")) {
			return;
		}
		$w.data("querying_daily", true);
		
		var wurl = main.contextPath + "/world/music/chart/query?period=daily&page=" + this.dailyPage;
		var $daily_100_loading = $("#daily_100_div > div.loadingBox");
		$daily_100_loading.show();
		
		$.get(wurl, function(result){
			$daily_100_loading.before(result);
			chart_index.dailyPage += 1;
		}).complete(function(){
			$daily_100_loading.hide();
			$w.data("querying_daily", false);
			$w.data("scrolling", false);
		});		
	}
};